package com.bear;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.concurrent.Executor;

/** nacos监听器
 * @author LiuShanshan
 * @version V1.0
 * @Description
 */
public class SimpleDemo2Listenter {
    public static void main(String[] args) throws NacosException {
        //nacos 地址
        final String serverAddr = "127.0.0.1:8848";
        //Data Id
        String dataId = "nacos-simple-demo.yaml";
        //Group
        String group = "DEFAULT_GROUP";
        Properties properties = new Properties();
        properties.put("serverAddr",serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        //获取配置,String dataId, String group, long timeoutMs
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);

        // 添加监听器，监听nacos是否有配置变动
        configService.addListener(dataId, group, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                // 监听器只能使用于public环境
                // nacos配置变动，则此处可响应
                System.out.println("配置变动");
                System.out.println(configInfo);

            }
        });

        // nacos监听器是守护线程，当主线程结束，监听器也会结束
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
